#!/usr/bin/env python
"""
v0.1
    1，查找并连接WiFi；                                            ok
    2，通过“requests”模块来完成WiFi的自动登录；                   ok
        2.1：输入账号密码，选择运营商，并保存到文件                  ok
        2.1：先使用自己的账号密码完成静态自动登录；                  ok
        2.3：连接后，把能连接成功的账号密码分别保存，方便后期使用；   ok
        2.4：第二次连接时首先验证 之前输入的；
v0.2:
    1，输入错误，重新输入；ok
    2，输出程序运行时间；ok
    3，修改配置文件的的位置到"C:/ProgramData/校园网登录/UserData.ini"，ok
    4，添加作者。ok
v0.3:
    1,修改ping baidu 的延迟时间至0.5s
    2，优化UI
    3，在登录前初始化，防止重复登录
    4，配置文件使用相对路径。
"""

import re
import time
import requests
import pywifi
from os import system

url_0 = r"http://172.30.4.129/a70.htm"
url_post = r"http://172.30.4.129/a70.htm?isReback=1"
url_host = r"http://172.30.4.129/"

operator_list = (('移动', "@cmcc"), ('联通', '@unicom '), ('电信', '@telecom'))
post_information = {
    '0MKKey': '123456',
    'buttonClicked': '',
    'cmd': '',
    'DDDDD': '用户名@运营商代码',
    'err_flag': '',
    'Login': '',
    'para': '00',
    'password': '',
    'R1': '0',
    'R2': '',
    'R3': '0',
    'R6': '0',
    'redirect_url': '',
    'upass': '密码',
    'user': '',
    'username': ''}


def get_user_password():
    """从文件把用户名和密码变成列表方便遍历 """
    L = []
    with open(r"./UserData.ini", mode='r', encoding='utf-8') as user:
        for x in user:
            x = x.split("\t")
            list_ = x.pop()
            x.append(list_.split("\n")[0])
            L.append(x)
        return L


def wifi_find():
    wifi = pywifi.PyWiFi()
    card = wifi.interfaces()[0]
    card.scan()
    wifi_list = card.scan_results()
    for x in wifi_list:
        print(x.ssid)
        if x.ssid == "Huas-Student":
            return 1
    return 0


def wifi_interlinkage():
    wifi = pywifi.PyWiFi()  # 创建一个对象
    card = wifi.interfaces()[0]  # 选取一个网卡
    print(card.name())  # 输出网卡名称
    card.disconnect()  # 断开现有连接
    time.sleep(1)

    profile = pywifi.Profile()
    profile.ssid = "Huas-Student"
    card.connect(card.add_network_profile(profile))

    return 0


def initialize():
    """已登录返回：1，否则返回：0"""
    url = requests.get(url_host)
    url.encoding = "gbk"
    url = url.text
    BOOL = re.search("注销页", url, )
    if BOOL is not None:
        return 1
    else:
        return 0


def write_users():
    x = [input("UserName(按回车键继续):"), input("PassWord(按回车键继续):")]
    i = choose_operation()
    s = "\t".join(x) + '\t' + "\t".join(i) + "\n"
    with open(r'./UserData.ini', mode='w', encoding='utf-8') as f:
        f.write(s)
    return 0


def landing_text():
    cyclic = 0
    success_list = get_user_password()
    for x in success_list:
        cyclic += 1
        post_information['DDDDD'] = x[0] + x[3]
        post_information['upass'] = x[1]
        print(f"正在登陆\t账号：{x[0]}\t密码：{x[1]}\t运营商：{x[2]}")
        requests.post(url_post, data=post_information)
        if not initialize():
            print("登录失败")
            time.sleep(1)
        else:
            print("\n登录成功")
            return 0
    return 1


def choose_operation():
    while True:
        in_op = input("选择运营商，电信：1，移动：2，联通：3：")
        if in_op == "1":
            input_operation = ('电信', '@telecom')
            return input_operation
        elif in_op == "2":
            input_operation = ('移动', "@cmcc")
            return input_operation
        elif in_op == "3":
            input_operation = ('联通', '@unicom ')
            return input_operation
        else:
            print('输入错误')


def connect():
    return


if __name__ == "__main__":
    print('Editor:@李超群\n如果遇见BUG请发送邮件至"lichaoqun_01@163.com"')
    time.clock()
    print('正在检查网络...\n' + '*' * 60)
    n = 2
    while True:
        if system('@ping -n 1 -w 500 baidu.com') or system('@ping -n 1-w 500 qq.com'):
            print("*" * 60)
            try:
                print('正在准备登录...')
                if initialize():
                    print("--" * 30, "\n已经登录...\n可能是DNS出现问题")
                    break
                elif landing_text():
                    print("--" * 40,
                          "\n"
                          "登录失败，请检查账号密码是否正确，\n"
                          "如果无误，可能是：\n"
                          "1：已登录了2台设备：\n\t可到“http://172.30.0.200:8080/Self/nav_login”查看。\n"
                          "2：系统错误"
                          "如果输入账号密码错误，直接在下面输入新的。")
                    write_users()
                    n -= 1
                else:
                    var = None
            except requests.exceptions.ConnectionError:
                print("正在连接WIFI...")
                wifi_find()
                wifi_interlinkage()
                if n < 3:
                    print("连接失败，3s后重试")
                n -= 1
                time.sleep(3)
            except FileNotFoundError:
                print("--" * 30, "\n没有找到配置文件\n你可能删掉了它或者第一次登陆\n请输入你的校园网登录账户名和密码...")
                write_users()
        else:
            print("*" * 60, "\n电脑有链接，无需登录")
            break
        if n <= 0:
            print("------------------仔细想想啊，别再错啦----------------------")
    print('-' * 60, "\n登录时间：", time.clock(), "秒\n"
                                             + "--" * 30, "\n窗口3秒后关闭...", )
    time.sleep(3)
